const Koa = require('koa')
const bodyParser = require('koa-bodyparser')
const logger = require('koa-logger')
const userRoutes = require('./routes/users')
console.log('路由文件加载成功:', __dirname + '/routes/users.js')

const app = new Koa()

// 添加CORS支持
app.use(async (ctx, next) => {
  ctx.set('Access-Control-Allow-Origin', '*');
  ctx.set('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');
  ctx.set('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, OPTIONS');
  
  if (ctx.method === 'OPTIONS') {
    ctx.status = 200;
    return;
  }
  
  try {
    await next();
  } catch (err) {
    console.error('请求处理错误:', err);
    ctx.status = err.status || 500;
    ctx.body = {
      code: ctx.status,
      message: err.message || '服务器内部错误'
    };
    ctx.app.emit('error', err, ctx);
  }
});

// 请求日志中间件
app.use(async (ctx, next) => {
  const start = Date.now();
  console.log(`开始处理请求: ${ctx.method} ${ctx.url}`);
  await next();
  const ms = Date.now() - start;
  console.log(`请求处理完成: ${ctx.method} ${ctx.url} - ${ctx.status} - ${ms}ms`);
});

// 中间件
app.use(logger())
app.use(bodyParser({
  enableTypes: ['json'],
  jsonLimit: '10mb',
  strict: true,
  onerror: function(err, ctx) {
    console.error('请求体解析失败:', err);
    ctx.throw(400, '请求体解析失败')
  }
}))

// 路由
app.use(userRoutes.routes()).use(userRoutes.allowedMethods())

// 错误处理
app.on('error', (err, ctx) => {
  console.error('Server error:', err)
})

const PORT = process.env.PORT || 3000
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`)
})